package com.aaa.zs.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @fileName:IllegalIpFilter
 * @description:非法IP过滤功能
 * @author:zhz
 * @createTime:2020/11/20 10:30
 * @version:1.0.0
 */
@Component
public class IllegalIpFilter extends ZuulFilter {

    /**
     * 获取配置文件中配置的属性值，赋值给当前属性
     */
    @Value("${illegalIp}")
    private String illegalIps;
    /**
     * 定义过滤的类型（过滤器执行的时机）
     * @return
     */
    @Override
    public String filterType() {
        /**
         * pre   在业务之前执行
         * route  在执行业务时执行
         * post  在执行业务后执行
         * error 在执行业务发生异常时执行
         */
        return "pre";
    }

    /**
     * 执行顺序（当有多个过滤器时，返回值越小执行优先级越高）
     * @return
     */
    @Override
    public int filterOrder() {
        return 10;
    }

    /**
     * 确定该过滤器是否启用
     * @return
     */
    @Override
    public boolean shouldFilter() {
        //返回false  不启用   返回true 启用
        return true;
    }

    /**
     * 过滤器执行业务
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        System.out.println("进入了非法IP过滤器。。。。" );
        //使用zuul中RequestContext提供获取上下文对象方法获取上下文对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取HttpServletRequest
        HttpServletRequest request = currentContext.getRequest();
        //获取HttpServletResponse
        HttpServletResponse response = currentContext.getResponse();

        //获取请求IP地址
        String remoteAddr = request.getRemoteAddr();


        //判断ip地址是否合法 illegalIps=192.168.38.31.182,192.168.31.751.117,192.168.31.82,192.16
        if(illegalIps.contains(remoteAddr)){
       // if(remoteAddr.equals("192.168.31.117")||remoteAddr.equals("192.168.31.82")
        //        ||remoteAddr.equals("192.168.31.75")||remoteAddr.equals("192.168.31.182")){
            //程序不再继续
            currentContext.setSendZuulResponse(false);
            //防止相应中文乱码
            response.setCharacterEncoding("utf-8");
            try {
                response.sendError(HttpStatus.SC_FORBIDDEN,"你的IP被禁止访问。。。");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
